package com.example.security;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.common.entity.LoginInfo;
import com.example.sys.entity.User;
import com.example.sys.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loginByUsernameOrPhone(username);
        if(ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user, loginInfo);
        loginInfo.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        loginInfo.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoleName()));
        return loginInfo;
    }
}
